<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="username" label="用户名" required>
				<uni-easyinput v-model="formData.username" :clearable="false" placeholder="请输入用户名" />
			</uni-forms-item>
			<uni-forms-item :name="showPassword ? 'password' : ''" label="重置密码">
				<span v-show="!showPassword" class="reset-password-btn" @click="trigger">点击重置密码</span>
				<uni-easyinput v-show="showPassword" v-model="formData.password" :clearable="false" placeholder="请输入重置密码">
					<view slot="right" class="cancel-reset-password-btn" @click="trigger">取消</view>
				</uni-easyinput>
			</uni-forms-item>
			
			<uni-forms-item name="gender" label="性别" required>
				<uni-data-select v-model="formData.gender" :localdata="enumGenderList.getnder_list">
				</uni-data-select>
			</uni-forms-item>
			
			<!-- 云端数据 -->
			<uni-forms-item label="机构选择" v-if="hasAdmin">
				<uni-data-select :localdata="mechanismList"  :page-size="500" field="_id as value, name as text" 
					v-model="mechanism_id" :clear="false" />
			</uni-forms-item>
			
		<!-- 	<uni-forms-item name="role" label="角色列表" class="flex-center-x">
				<uni-data-checkbox multiple :localdata="roles" v-model="formData.role" />
			</uni-forms-item> -->
		<!-- 	<uni-forms-item name="tags" label="用户标签" labelWidth="100" class="flex-center-x">
				<uni-data-checkbox :multiple="true" v-model="formData.tags" collection="uni-id-tag"
					field="tagid as value, name as text"></uni-data-checkbox>
				<span class="link-btn" @click="gotoTagAdd">新增</span>
				<span class="link-btn" @click="gotoTagList" style="margin-left: 10px;">管理</span>
			</uni-forms-item> -->
	<!-- 		<uni-forms-item name="dcloud_appid" label="可登录应用" class="flex-center-x">
				<uni-data-checkbox :multiple="true" v-model="formData.dcloud_appid" 
				:where="appwhere"
				collection="opendb-app-list"
					field="appid as value, name as text"></uni-data-checkbox>
				<span class="link-btn" @click="gotoAppList">管理</span>
			</uni-forms-item> -->
			<uni-forms-item name="mobile" label="手机号">
				<uni-easyinput v-model="formData.mobile" :clearable="false" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item name="email" label="邮箱">
				<uni-easyinput v-model="formData.email" :clearable="false" placeholder="请输入邮箱" />
			</uni-forms-item>
			<uni-forms-item name="status" label="用户状态" v-if="cur_role==='xueshen'?false:true">
				<switch v-if="Number(formData.status) < 2" @change="binddata('status', $event.detail.value)" :checked="formData.status" />
				<view v-else class="uni-form-item-empty">{{parseUserStatus(formData.status)}}</view>
			</uni-forms-item>
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button" @click="submitForm">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;" class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import { validator ,enumConverterStudent,enumConverterGender,enumGenderList} from '@/js_sdk/validator/uni-id-users.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'uni-id-users';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			return {
				enumGenderList,
				enumConverterStudent,
				showPassword: false,
				formData: {
					"username": "",
					"password": "",
					"role": ['jigou'],
					"dcloud_appid": ['__UNI__653656E'],
					"mobile": "",
					"mechanism_id":"",
					"email": "",
					"status": false ,//默认禁用
					"type_subject_id": "",
					"type_drive_id": "",
					"type_cert_id": "",
					"id_card": "",
					"tuition": 0,
					"test_times": 0,
					"fee_status": 0,
					"use_times": 0,
					"recommender": "",
					"recommender_mobile": "",
					"student_name": "",
					"subject_page_ids": [],
					"gender":0
				},
				rules: {
					...getValidator(["username", "password", "role", "mobile", "email"]),
					"status": {
						"rules": [{
							"format": "bool"
						}]
					}
				},
				roles: [{
					value: "jigou",
					text: "机构"
				}],
				mechanism_id:'',
				roleList:[],
				appwhere:{},
				cur_role: '',
				subjectList: [],
				hasAdmin:false ,
				mechanismList:[]
			}
		},
		onLoad(e) {
			const id = e.id
			
			if (this.uniIDHasRole('admin')) {
				this.hasAdmin = true 
			}
			
			if (e.mechanism) {
				this.mechanism_id = e.mechanism
				// this.roleList.push(e.role)
				// if(e.role == 'xueshen'){
				// 	this.appwhere={
				// 		name:'练习系统'
				// 	}
				// 	this.cur_role = 'xueshen'
				// }else{
				// 	this.appwhere={
				// 		name:'PC'
				// 	}
				// }
			}
			this.cur_role = 'jigou'
			this.appwhere = {
				name: 'PC'
			}
			this.formDataId = id
			this.getMechanismList()
			this.getDetail(id)
			//this.loadroles()
		},
		watch: {
			"formData.type_subject_id":function(nv){
					
				if(this.formData.type_drive_id && this.formData.type_cert_id){
					this.getSubjectList()
				}
			},
			"formData.type_cert_id": function(nv, ov) {
				console.log(nv, ov)
				if (nv) {
					this.getSubjectList()
				}
			}
		},
		
		methods: {
			async getMechanismList(){
				const response = await db.collection('mechanism').field("_id as value, name as text").limit(500).get()
				for (let s of response.result.data) {
					this.mechanismList.push(s)
				}
			},
			async getSubjectList() {
				this.subjectList = [] 
			// 	const data = await db.collection('mechanism-subject-list,subject-page')
			
			// 		.where({
			// 			// mechanism_id: db.command.eq(this.mechanism_id),
			// 			'subject_id.type_subject': db.command.eq(this.formData.type_subject_id)
			// 			// ['subject_id.type_drive_id']: db.command.in([this.formData.type_drive_id])
			// 		})
			// 		.field('_id,mechanism_id,subject_id,suject_id{_id,name,s_id,type_subject,type_drive_id}')
			// 		.limit(500)
			// 		.get()
					
					const mesubjectList = await db.collection('mechanism-subject-list')
								
						.where({
							mechanism_id: db.command.eq(this.mechanism_id),
							// 'subject_id.type_subject': db.command.eq(this.formData.type_subject_id)
							// ['subject_id.type_drive_id']: db.command.in([this.formData.type_drive_id])
						})
						.getTemp();
						// .field('_id,mechanism_id,subject_id,suject_id{_id,name,s_id,type_subject,type_drive_id}')
						// .limit(500)
						// .get()
					const subject = await db.collection('subject-page').where({
						type_subject:db.command.eq(this.formData.type_subject_id),
						type_drive_id:db.command.in([this.formData.type_drive_id])
					}).getTemp()
					const data = await db.collection(mesubjectList,subject).get()
					
			
				if (data.result.data.length > 0) {
					let subjectlist = data.result.data[0].subject_id 
					for (let s of subjectlist) {
						this.subjectList.push({value:s.s_id,text:s.name})
					}
				}
			},
			setCertValue(value) {
				this.formData.type_cert_id = ''
				this.$nextTick(() => {
					for (let s of this.$refs.drive_udb.mixinDatacomResData) {
						if (s.value === value) {
							this.showCertText = s.type_cert_id[0].name
							this.formData.type_cert_id = s.type_cert_id[0].s_id
						}
					}
				})
			
			},
			
			/**
			 * 跳转应用管理的 list 页
			 */
			gotoAppList() {
				uni.navigateTo({
					url: '../app/list'
				})
			},
			gotoTagList() {
				uni.navigateTo({
					url: '../tag/list'
				})
			},
			gotoTagAdd() {
				uni.navigateTo({
					url: '../tag/add',
					events: {
						refreshCheckboxData: () => {
							this.$refs.checkbox.loadData()
						}
					}
				})
			},
			/**
			 * 切换重置密码框显示或隐藏
			 */
			trigger() {
				this.showPassword = !this.showPassword
			},

			/**
			 * 触发表单提交
			 */
			submitForm(form) {
				this.$refs.form.submit();
			},

			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail
				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				uni.showLoading({
					title: '修改中...',
					mask: true
				})

				// 是否启用功能的数据类型转换， 0 正常， 1 禁用
				if (typeof value.status === "boolean") {
					value.status = Number(!value.status)
				}
				if (typeof value.fee_status === "boolean") {
					value.fee_status = Number(!value.fee_status)
				}
				console.log(value)
				value.password = this.formData.password
				value.id = this.formDataId
				value.mechanism_id = this.mechanism_id
				value["dcloud_appid"]=['__UNI__653656E']
				value['role']=['jigou']
					
				this.$request('updateUser', value, {
					functionName: 'uni-id-cf'
				}).then(res => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(err => {
					uni.hideLoading()
				})
			},

			resetPWd(resetData) {
				this.$request('system/user/resetPwd', resetData)
					.then().catch(err => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally()
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName)
					.doc(id)
					.field('username,mechanism_id,role,dcloud_appid,gender,tags,mobile,email,status,type_subject_id,type_drive_id,type_cert_id,id_card,tuition,test_times,fee_status,use_times,recommender,recommender_mobile,student_name,subject_page_ids')
					.get()
					.then((res) => {
						const data = res.result.data[0]
						if (data) {
							if (data.status === undefined) {
								data.status = true
							}
							if (data.status === 0) {
								data.status = true
							}
							if (data.status === 1) {
								data.status = false
							}
							this.formData = Object.assign(this.formData, data)
							this.mechanism_id = this.formData.mechanism_id
						}
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
			},
			loadroles() {
				let where = {} 
				if(this.roleList.length>0){
					
					where['role_id'] = db.command.in([this.roleList[0]])
				}
				console.log(where)
				
				db.collection('uni-id-roles').where(where).limit(500).get().then(res => {
					const roleIds = []
					this.roles = res.result.data.map(item => {
						roleIds.push(item.role_id)
						return {
							value: item.role_id,
							text: item.role_name
						}
					})
					if (roleIds.indexOf('admin') === -1 && this.mechanism_id=='') {
						this.roles.unshift({
							value: 'admin',
							text: '超级管理员'
						})
					}
				}).catch(err => {
					uni.showModal({
						title: '提示',
						content: err.message,
						showCancel: false
					})
				})
			},
			// status 对应文字显示
			parseUserStatus(status) {
				if (status === 0) {
					return '启用'
				} else if (status === 1) {
					return '禁用'
				} else if (status === 2) {
					return '审核中'
				} else if (status === 3) {
					return '审核拒绝'
				} else {
					return '启用'
				}
			}
		}
	}
</script>

<style>
	.reset-password-btn {
		/* height: 100%; */
		line-height: 36px;
		color: #007AFF;
		text-decoration: underline;
		cursor: pointer;
	}

	.cancel-reset-password-btn {
		color: #007AFF;
		padding-right: 10px;
		cursor: pointer;
	}
	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}
</style>
